import datetime
import os.path
import time
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import sys
import logging
import pywintypes
import win32timezone
script_dir = os.path.dirname(sys.argv[0])

logger = None

ServiceName = "PythonServiceTemplate"
ServiceNameDisplay = "PythonServiceTemplateDisplay"


def main():
    while closeevent.isrun():
        clonselog('Service is running...')
        time.sleep(0.5)


def clonselog(log: str, infolevel: str = 'info'):
    now = datetime.datetime.now()
    logpath = script_dir + "\\log\\{}.log".format(now.strftime('%Y-%m-%d'))
    logstr = f"[{infolevel}] | {now.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]} | {log}"
    print(logstr)
    isonemkdir = False
    if not os.path.exists(script_dir + '\\log'):
        os.makedirs(script_dir + '\\log')
    if not os.path.isfile(logpath):
        isonemkdir = True
    with open(logpath, "a", encoding="utf-8") as f:
        if isonemkdir:
            f.write(logstr)
        else:
            f.write("\n" + logstr)


class closeEvent:
    def __init__(self):
        self.isRunning = True


    def close(self):
        self.isRunning = False


    def isrun(self):
        return self.isRunning


closeevent = closeEvent()


class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = ServiceName
    _svc_display_name_ = ServiceNameDisplay


    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)


    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        closeevent.close()


    def SvcDoRun(self):
        global logger
        servicemanager.LogMsg(
                servicemanager.EVENTLOG_INFORMATION_TYPE,
                servicemanager.PYS_SERVICE_STARTED,
                (self._svc_name_, '')
                )
        logger = self.setup_logger()
        main()


    def setup_logger(self):
        logger = logging.getLogger('MyService')
        logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('my_service.log')
        logger.addHandler(handler)
        return logger


if __name__ == '__main__':
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(MyService)
        try:
            servicemanager.StartServiceCtrlDispatcher()
        except pywintypes.error:
            main()
    else:
        win32serviceutil.HandleCommandLine(MyService)
